package com.zyj.rfidscanner.controller;

import com.github.pagehelper.PageInfo;
import com.zyj.assets.domain.AssetsInfo;
import com.zyj.check.domain.AssetsCheck;
import com.zyj.check.domain.AssetsCheckDetail;
import com.zyj.check.mapper.AssetsCheckMapper;
import com.zyj.check.service.IAssetsCheckService;
import com.zyj.common.constant.Constants;
import com.zyj.common.core.controller.BaseController;
import com.zyj.common.core.domain.AjaxResult;
import com.zyj.common.core.page.TableDataInfo;
import com.zyj.common.core.text.Convert;
import com.zyj.common.utils.DateUtils;
import com.zyj.common.utils.ServletUtils;
import com.zyj.common.utils.StringUtils;
import com.zyj.common.utils.uuid.UUID;
import com.zyj.system.service.ISysDeptService;
import com.zyj.system.service.ISysDictDataService;
import com.zyj.system.service.ISysUserService;
import com.zyj.token.domain.AssetsLoginToken;
import com.zyj.token.service.IAssetsLoginTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by zyjaz on 2022/5/21.
 */
@Api("扫码枪接口")
@Controller
@RequestMapping("/scanner/api")
public class RfidScannerController extends BaseController {

    @Autowired
    private IAssetsLoginTokenService assetsLoginTokenService;

    @Autowired
    private IAssetsCheckService assetsCheckService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private AssetsCheckMapper assetsCheckMapper;


    //登录接口
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            String tokenStr = UUID.randomUUID().toString().replace("-","");
            Map map = getLoginMap(tokenStr);
            //保存登录信息到assets_login_token，下次自动登录
            AssetsLoginToken assetsLoginToken = new AssetsLoginToken();
            assetsLoginToken.setUsername(username);
            assetsLoginToken.setToken(tokenStr);
            assetsLoginToken.setPassword(password);
            assetsLoginTokenService.insertAssetsLoginToken(assetsLoginToken);
            return AjaxResult.success(map);
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    /**
     * 检查token
     */
    @GetMapping("/checklogin/{tokenStr}")
    @ResponseBody
    public AjaxResult checklogin(@PathVariable("tokenStr") String tokenStr)
    {
        AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(tokenStr);
        if(atoken == null){
            String msg = "token不存在";
            return error(msg);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(atoken.getUsername(), atoken.getPassword(), false);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            Map map = getLoginMap(tokenStr);
            return AjaxResult.success(map);
        }
        catch (AuthenticationException e)
        {
            String msg = "用户名或密码不正确";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    private Map getLoginMap(String tokenStr){
        Map map = new HashMap<>();
        map.put("token",tokenStr);
        map.put("userId",getUserId());
        map.put("loginName",getLoginName());
        map.put("userName",getSysUser().getUserName());
        map.put("deptId",getSysUser().getDeptId());
        map.put("deptName",getSysUser().getDept().getDeptName());
        return map;
    }


    //获取正在盘点的任务列表
    @PostMapping("/checklist")
    @ResponseBody
    public TableDataInfo checklist(AssetsCheck assetsCheck,
                                   @RequestHeader(value = "token",required = false) String token)
    {
        if(token == null || "".equals(token)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(500);
            rspData.setMsg("Token不正确！");
            rspData.setRows(new ArrayList<>());
            rspData.setTotal(0);
            return rspData;
        }else{
            AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(token);
            if(atoken == null){
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(500);
                rspData.setMsg("Token不正确！");
                rspData.setRows(new ArrayList<>());
                rspData.setTotal(0);
                return rspData;
            }
        }
        assetsCheck.setCheckStatus("1");
        startPage();
        List<Map<String,String>> resultList = new ArrayList<>();
        List<AssetsCheck> list = assetsCheckService.selectAssetsCheckList(assetsCheck);
        if(list!=null && !list.isEmpty()){
            for(int i=0;i<list.size();i++){
                AssetsCheck ac = list.get(i);
                Map<String,String> map = new HashMap<>();
                map.put("checkId",ac.getCheckId()+"");
                map.put("checkNo",ac.getCheckNo());
                map.put("checkName",ac.getCheckName());
                map.put("checkNum",ac.getCheckNum()+"");
                map.put("createTime", DateUtils.dateTime(ac.getCreateTime()));
                map.put("createBy",ac.getCreateBy());
                resultList.add(map);
            }

        }
        return getDataTable(resultList);
    }

    //查询盘点任务详情
    /**
     * 资产盘点详情
     */
    @GetMapping("/checkdetail/{checkId}")
    @ResponseBody
    public AjaxResult detail(@PathVariable("checkId") Long checkId,
                         @RequestHeader(value = "token",required = false) String token)
    {
        if(token == null || "".equals(token)){
            return error("Token不正确");
        }else{
            AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(token);
            if(atoken == null){
                return error("Token不正确");
            }
        }
        return AjaxResult.success(getDetail(checkId));
    }

    //上报扫描仪盘点结果
    @PostMapping("/checkupload")
    @ResponseBody
    public AjaxResult checkupload(AssetsCheck assetsCheck,
                                   @RequestHeader(value = "token",required = false) String token)
    {
        AssetsCheckDetail assetsCheckDetail = new AssetsCheckDetail();
        if(token == null || "".equals(token)){
            return error("Token不正确");
        }else{
            AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(token);
            if(atoken == null){
                return error("Token不正确");
            }
            UsernamePasswordToken usertoken = new UsernamePasswordToken(atoken.getUsername(), atoken.getPassword(), false);
            Subject subject = SecurityUtils.getSubject();
            subject.login(usertoken);
            //获取盘点人
            assetsCheckDetail.setUserId(getUserId());
            assetsCheckDetail.setUserName(getSysUser().getUserName());
            assetsCheckDetail.setCreateBy(getLoginName());
            assetsCheckDetail.setCheckUserId(assetsCheckDetail.getUserId());
            assetsCheckDetail.setCheckUserName(assetsCheckDetail.getUserName());
        }

        Long checkId = assetsCheck.getCheckId();
        String checkNo = assetsCheck.getCheckNo();
        System.out.println(checkId + "|" + checkNo);
        assetsCheckDetail.setCheckId(checkId);
        assetsCheckDetail.setAssetsSn(checkNo);
        assetsCheckDetail.setCheckFlag("1");
        assetsCheckDetail.setCheckTime(new Date());
        int result = assetsCheckService.updateAssetsCheckDetails(assetsCheckDetail);
        System.out.println("result="+result);
        if(result<0){
            return error("盘点数据上传失败！");
        }
        return AjaxResult.success(getDetail(checkId));
    }




    private Map getDetail(Long checkId){
        AssetsCheck assetsCheck = assetsCheckService.selectAssetsCheckByCheckId(checkId);
        if(assetsCheck.getCheckDepts()!=null && !"".equals(assetsCheck.getCheckDepts())) {
            assetsCheck.setCheckDeptsName(deptService.selectDeptById(Long.parseLong(assetsCheck.getCheckDepts())).getDeptName());
        }else{
            assetsCheck.setCheckDeptsName("所有");
        }
        //查询已经完成和未完成
        int nofinash = assetsCheckService.selectAssetsCheckDetailCount(checkId,0);
        int finash = assetsCheckService.selectAssetsCheckDetailCount(checkId,1);
        String type = "";
        String status = "";
        Map map = new HashMap<>();
        if(assetsCheck.getCheckAssetsType()!=null && !"".equals(assetsCheck.getCheckAssetsType())){
            String types = assetsCheck.getCheckAssetsType();
            String typesarray [] = types.split(",");
            for(int i=0;i<typesarray.length;i++){
                String t = typesarray[i];
                type += dictDataService.selectDictLabel("assets_type", t)+",";
            }
            type = type.substring(0,type.length()-1);
        }else{
            type = "所有";
        }
        if(assetsCheck.getCheckAssetsStatus()!=null && !"".equals(assetsCheck.getCheckAssetsStatus())){
            String statuss = assetsCheck.getCheckAssetsStatus();
            String statussarray [] = statuss.split(",");
            for(int i=0;i<statussarray.length;i++){
                String t = statussarray[i];
                status += dictDataService.selectDictLabel("assets_status", t)+",";
            }
            status = status.substring(0,status.length()-1);
        }else{
            status = "所有";
        }

        map.put("type", type);
        map.put("status", status);
        map.put("dept", assetsCheck.getCheckDeptsName());
        map.put("nofinash", nofinash);
        map.put("finash", finash);
        return map;
    }



    @GetMapping("/getSnKey")
    @ResponseBody
    public AjaxResult getSnKey(@RequestHeader(value = "token",required = false) String token)
    {
        if(token == null || "".equals(token)){
            return error("Token不正确");
        }else{
            AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(token);
            if(atoken == null){
                return error("Token不正确");
            }
        }

        for(Object key : (Constants.makeSnKey).keySet()){
            return AjaxResult.success(key);
        }
        return AjaxResult.success();

    }

    @GetMapping("/sendSnNo/{key}/{sn}")
    @ResponseBody
    public AjaxResult sendSnNo(@PathVariable("key") String key,@PathVariable("sn") String sn,
                             @RequestHeader(value = "token",required = false) String token)
    {
        if(token == null || "".equals(token)){
            return error("Token不正确");
        }else{
            AssetsLoginToken atoken = assetsLoginTokenService.selectAssetsLoginTokenByToken(token);
            if(atoken == null){
                return error("Token不正确");
            }
        }
        Constants.makeSnKey.put(key,sn);
        return AjaxResult.success();
    }

}
